package com.qdy.web;

import com.jiai.core.tools.RestResultGenerator;
import com.jiai.core.util.SpringUtil;
import com.jiai.exception.ServiceException;
import com.qdy.config.Config;
import com.qdy.util.UploadUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.UUID;

/**
 * Created by qudingyi on 2017/4/7.
 */
@RequestMapping("/file")
@RestController
public class FileController {
    private static final Logger log= LoggerFactory.getLogger(FileController.class);
    @Autowired
    private Config config;

    @RequestMapping("/uploadImage")
    public Object upload(@RequestParam("file") MultipartFile file)throws ServiceException {
        String newName="";
        try {
            String filePath = SpringUtil.getBean(Config.class).getSavePath();
            newName= UUID.randomUUID() + UploadUtil.getExtName(file.getOriginalFilename(), '.');
            filePath += File.separator + "image" + File.separator + newName;
            if (file.isEmpty()) {
                return RestResultGenerator.genErrorResult("文件不存在");
            }
            File dest=new File(filePath);
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            file.transferTo(dest);
            return RestResultGenerator.genSuccessResult(newName);

        }catch (Exception e){
           return RestResultGenerator.genErrorResult(e.getMessage());
        }
      }


    @RequestMapping("/downloadImage")
    public void  downlaodImg(HttpServletResponse response,String fileName){
        try{
            response.setContentType("image/png");
            String uploadPath=config.getSavePath()+File.separator+"image"+File.separator+fileName;
            File file=new File(uploadPath);
            FileInputStream inputStream = new FileInputStream(file);
            byte[] data = new byte[(int)file.length()];
            int length = inputStream.read(data);
            inputStream.close();
            OutputStream stream = response.getOutputStream();
            stream.write(data);
            stream.flush();
            stream.close();
        }catch (Exception e){
            log.error("图片下载失败!error:[{}]",e.getMessage());
        }

    }
}
